<template>
  <el-card style="max-width: 600px; margin: 50px auto;">
    <template #header>
      <div style="text-align: center;">
        <h2>修改权限信息</h2>
      </div>
    </template>
    
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="权限ID" prop="PermissionId">
        <el-input v-model="formData.PermissionId" disabled />
      </el-form-item>
      
      <el-form-item label="权限名" prop="PermissionName">
        <el-input v-model="formData.PermissionName" placeholder="请输入权限名" />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存修改</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import axios from 'axios';

interface Permission {
  PermissionId: number;
  PermissionName: string;
}

const route = useRoute();
const router = useRouter();
const formRef = ref<FormInstance>();

const formData = ref<Permission>({
  PermissionId: 0,
  PermissionName: ''
});

const rules = ref<FormRules>({
  PermissionName: [
    { required: true, message: '请输入权限名', trigger: 'blur' },
    { min: 2, max: 20, message: '权限名长度在2到20个字符', trigger: 'blur' }
  ]
});

// 获取权限详情
const getPermissionDetail = () => {
  try {
    const permissionId = route.params.id;
    
      axios({
        url:"http://localhost:5028/api/Management/GetPermissionDetail",
        method:"get",
        params:{
          PermissionId:permissionId
        }
      })
      .then(res=>{
        console.log(res)
        if(res.data.Code===200){
          formData.value=res.data.Result;
        }else{
          ElMessage.error(res.data.Message);
        }
      })
    
  } catch (error) {
    ElMessage.error('获取权限信息失败');
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    const response = await axios.put('http://localhost:5117/api/Operate/UpdatePermission', formData.value);
    console.log(response)
    if (response.data.Code === 400) {
      ElMessage.success('修改成功');
      router.push('/showPermission');
    } else {
      ElMessage.error(response.data.Message || '修改失败');
    }
  } catch (error: any) {
    if (error.response?.data?.Message) {
      ElMessage.error(error.response.data.Message);
    } else {
      ElMessage.error('修改失败');
    }
  }
};

// 返回
const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  getPermissionDetail();
});
</script>

<style scoped>
.el-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 20px;
}
</style>